package com.mars.filter;

import com.mars.common.RequestHolder;
import com.mars.pojo.SysUser;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 拦截用户登陆的请求
 * @author MARS
 * @date 2018/1/14
 */

@Slf4j
public class LoginFilter  implements Filter{


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        // 获取请求的url
        // String servletPath = req.getServletPath();
        String root = req.getContextPath();

        SysUser sysUser = (SysUser) req.getSession().getAttribute("user");
        if (sysUser == null) {
            String path = root+"/signin.jsp";
            resp.sendRedirect(path);
            return ;
        }

        RequestHolder.add(sysUser);
        RequestHolder.add(req);

        // 登陆成功后
        filterChain.doFilter(servletRequest,servletResponse);
        return;
    }

    @Override
    public void destroy() {

    }
}
